﻿/*****************************************介绍*****************************************
 * 作者：Ywh
 * 创建时间：2023-09-07　04:14:33
 * 功能：图片和Base64之间互相换换
**************************************************************************************/

using Game.Framework;
using System;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class PictureAndBase64_Convert
{
    private const string BASE64_HEAD = "data:image/png;base64,";

    [MenuItem("Assets/CustomTools/图片转换操作/图片转Base64", priority = 12)]
    private static void ToBase64()
    {
        var type = Selection.activeObject.GetType();
        if (type == typeof(Texture2D))
        {
            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
            string base64Str = Convert.ToBase64String(File.ReadAllBytes(path));
            string savePath = path.Replace(Path.GetExtension(path), "_base64.txt");

            //File.WriteAllText(savePath, BASE64_HEAD + base64Str);
            //AssetDatabase.Refresh();

            // 复制到剪切板
            GUIUtility.systemCopyBuffer = BASE64_HEAD + base64Str;
            EditorUtility.DisplayDialog("转换结果", $"成功将【{Path.GetFileNameWithoutExtension(path)}】转为 Base64字符串，已复制到剪切板！！", "OK");
        }
    }

    [MenuItem("Assets/CustomTools/图片转换操作/Base64转图片", priority = 13)]
    private static void ToTexture()
    {
        var type = Selection.activeObject.GetType();
        if (type == typeof(TextAsset))
        {
            string path = AssetDatabase.GetAssetPath(Selection.activeObject);
            if (Path.GetFileNameWithoutExtension(path).Contains("_base64"))
            {
                string base64Str = File.ReadAllText(path);
                string finalStr = base64Str.StartsWith(BASE64_HEAD) ? base64Str.Substring(BASE64_HEAD.Length) : base64Str;
                byte[] bytes = Convert.FromBase64String(finalStr);

                Texture2D tex = new Texture2D(2, 2);
                tex.LoadImage(bytes);
                LogManager.Log(tex.width);
                LogManager.Log(tex.height);
                Transform canvs = GameObject.Find("Canvas/Dynamic").transform;
                string name = Path.GetFileNameWithoutExtension(path);
                Image img = new GameObject(name).AddComponent<Image>();
                img.transform.SetParent(canvs);
                img.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.one * 0.5f);
                img.SetNativeSize();
                //byte[] saveData = tex.EncodeToJPG();
                //string savePath = path.Replace(Path.GetExtension(path), ".jpg");
                //File.WriteAllBytes(savePath, saveData);
                //AssetDatabase.Refresh();
            }
        }
    }
}
